<script setup lang="ts">
import { ref, watch } from 'vue';
import { $t } from '@/locales';
import { useForm, useFormRules } from '@/hooks/common/form';
import { fetchRoleAll, fetchSaveRoleRelation } from '@/service/api';
import { useLoading } from '~/packages/hooks';

defineOptions({ name: 'RoleSelectDialog' });

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

interface Props {
  objId?: CommonType.IdType;
  type?: string;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

type FormModel = Api.System.Role.RoleRelationFormModel;

function createDefaultModel(): FormModel {
  return {
    objId: props.objId,
    type: props.type,
    roleIds: []
  };
}

const { formRef, validate, restoreValidation } = useForm();
const { createRequiredRule } = useFormRules();

const model = ref<FormModel>(createDefaultModel());

// 初始化
function handleInitModel() {
  model.value = createDefaultModel();
}

type RuleKey = Extract<FormModel, 'roleIds'>;
const rules = ref<Record<RuleKey, App.Global.FormRule>>({
  roleIds: createRequiredRule('请选择')
});

const { loading, startLoading, endLoading } = useLoading(false);

async function handleSubmit() {
  try {
    await validate();
    startLoading();
    // request
    const { error } = await fetchSaveRoleRelation(model.value);
    // success
    if (error) return;
    window.$message?.success($t('common.operateSuccess'));
    closeDialog();
    emit('submitted');
  } finally {
    endLoading();
  }
}

const roleList = ref<Api.System.Role.RoleInfoRecord[]>();

async function listRoleAll() {
  const { data, error } = await fetchRoleAll();
  if (error) return;
  roleList.value = data;
}

// 关闭对话框
function closeDialog() {
  visible.value = false;
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    listRoleAll();
  }
});
</script>

<template>
  <ElDialog
    v-model="visible"
    :title="type === 'USER' ? '用户角色' : '部门角色'"
    width="600"
    :close-on-click-modal="false"
  >
    <ElForm ref="formRef" v-loading="loading" :model="model" :rules="rules" :label-width="80" label-position="top">
      <ElFormItem label="选择角色" prop="roleIds">
        <ElSelect v-model="model.roleIds" multiple collapse-tags collapse-tags-tooltip>
          <template v-for="item in roleList" :key="item.id">
            <ElOption :label="item.name" :value="item.id" />
          </template>
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElSpace v-loading="loading" :size="16">
        <ElButton @click="closeDialog">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
